package logic.entities;

import java.util.ArrayList;

import logic.characters.Player;
import logic.enemies.Enemy;
import logic.pruebas.GamePanel;

/**
 * @author Unai
 * Fondo de los niiveles, se mueve con el jugador
 *
 */
public class Background extends GameObject{
	private static final long serialVersionUID = -746220954114543629L;
	protected float velX;
	protected float velY;
	private Player player;
	private float initXCoord;
	private float initYCoord;
	public float antCoorX;
	public float antCoorY;
	private GamePanel panel;
	
	/**
	 * @param x
	 * @param y
	 * @param panel
	 * @param nomImg
	 * @param player
	 */
	public Background(float x, float y, GamePanel panel, String nomImg, Player player) {
		super(x, y, panel, nomImg);
		this.player = player;
		initXCoord = x;
		initYCoord = y;
		this.panel = panel;
	}

	/**
	 * @param enemies
	 * Se encarga de hace scroll y recolocar enemigos y jugador
	 */
	public void updateBackground(ArrayList<Enemy> enemies) {
		if (this.dibujado) {
			if (player.coorX + player.anchura > 500f) {
				velX = -300;
			} else if (player.coorX < 300f) {
				velX = 300;
			} else {
				velX = 0;
			}
			
			if (player.coorY > 350f) {
				velY = -350f;
			} else if (player.coorY + player.altura < 250f) {
				velY = 350f;
			} else {
				velY = 0f;
			}
			
			float tiempoTranscurridoEnSegundos = 
					(System.currentTimeMillis() - ultimoDibujo) / 1000.0F;
			if (tiempoTranscurridoEnSegundos > 0.01F) {
				antCoorX = coorX;
				antCoorY = coorY;
				coorX = coorX+velX * tiempoTranscurridoEnSegundos;
				coorY = coorY+velY * tiempoTranscurridoEnSegundos;
				if (coorX > 0 || coorX + anchura < 800) {
					velX = 0;
					coorX = antCoorX;
				}
				if (coorY + altura < 600 || coorY > 0) {
					velY = 0;
					coorY = antCoorY;
				}
				player.coorX = player.coorX + (coorX - antCoorX);
				player.coorY = player.coorY + (coorY - antCoorY);
				
				if (enemies != null) {

				for (Enemy enemy : enemies) {
					if (enemy != null && !enemy.dead) {
						enemy.coorX = enemy.coorX + (coorX - antCoorX);
						enemy.coorY = enemy.coorY + (coorY - antCoorY);
						
						if (enemy.coorX < coorX || enemy.coorX - enemy.anchura > coorX + anchura || enemy.coorY < coorY || enemy.coorY + enemy.altura > coorY + altura) {
							enemy.die();
						}

					}
				}
				}

			}
			dibujar();
			panel.drawTime();
		}

	}	
	
	public boolean seSaleX() {
		return (coorX < initXCoord - (this.anchura - 800) || coorX > initXCoord);
	}
	
	public boolean seSaleY() {
		return (coorY < initYCoord - (this.altura - 600) || coorY > initYCoord);
	}

}
